package com.synergy.stockflow.entity.vo;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.synergy.stockflow.entity.SysRole;
import com.synergy.stockflow.entity.SysUser;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.Date;
import java.util.List;

@Schema(description = "用户视图对象")
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SysUserVO implements Serializable {

    private static final long serialVersionUID = 1L;
    @Schema(description = "用户编号", example = "1")
    private Long id;
    @Schema(description = "账户名", example = "admin")
    private String username;
    @Schema(description = "昵称", example = "超级管理员")
    private String nickname;
    @Schema(description = "用户头像", example = "")
    private String avatar;
    @Schema(description = "邮箱", example = "")
    private String email;

    @Schema(description = "手机号", example = "138******88")
    private String phone;
    @Schema(description = "性别", example = "1")
    private Byte gender;
    @Schema(description = "状态", example = "启用")
    private Byte status;

    @Schema(description = "创建时间", example = "")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    private Date createTime;

    private transient List<SysRole> roles;

    // 手机号脱敏：138****1234
    private static String desensitizePhone(String phone) {
        if (phone == null || !phone.matches("\\d{11}")) {
            return phone;
        }
        return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
    }

    // 邮箱脱敏：zhan***@example.com
    private static String desensitizeEmail(String email) {
        if (email == null || !email.contains("@")) {
            return email;
        }
        int atIndex = email.indexOf("@");
        if (atIndex <= 3) {
            return email; // 防止太短
        }
        return email.substring(0, 3) + "***" + email.substring(atIndex);
    }


    /**
     * 构造方法或 Builder 可由 Service 层调用
     */
    public static SysUserVO fromEntity(SysUser user) {
        if (user == null) return null;

        SysUserVO vo = new SysUserVO();
        vo.setId(user.getId());
        vo.setUsername(user.getUsername());
        vo.setNickname(user.getNickname());
        vo.setAvatar(user.getAvatar());
        vo.setGender(user.getGender());
        vo.setStatus(user.getStatus());
        vo.setCreateTime(user.getCreateTime());

        // 脱敏处理
        vo.setEmail(desensitizeEmail(user.getEmail()));
        vo.setPhone(desensitizePhone(user.getPhone()));

        return vo;
    }

}